import type { PlasmoMessaging } from "@plasmohq/messaging"

import { getBaiduToken } from "~api/baiduchatAPI"
import { useTokenStroe } from "~store/tokenStore"
import type { AccessToken, TokenType } from "~type/tokenType"
import { OIAItype, OIAItypeObj } from "~util/AIUtil"

const handler: PlasmoMessaging.MessageHandler<TokenType> = async (req, res) => {
  console.log("access token...")
  const unsube = useTokenStroe.subscribe(console.log)
  useTokenStroe.setState({ tokenType: { ...req.body } })
  switch (req.body.aiSource) {
    case OIAItypeObj.baidu.type:
      const resMsg = await getBaiduToken(req.body)

      if (resMsg.status === 200) {
        const json = await resMsg.json<AccessToken>()
        console.log("token", json)
        useTokenStroe.setState({ accessToken: { ...json } })
        res.send({
          message: { status: resMsg.status, msg: "success", data: json }
        })
      }
      return
    case OIAItypeObj.chatgpt.type:
      useTokenStroe.setState({
        accessToken: { access_token: req.body.secretKey }
      })

      res.send({
        message: {
          status: 200,
          msg: "success",
          data: { access_token: req.body.secretKey }
        }
      })
      return
  }

  unsube()
  // console.log(req)
}

export default handler
